from wfs.function.pdfsign import *
from reportlab.lib.pagesizes import A4, landscape
from reportlab.pdfgen import canvas
from wfs.models import *
from django.conf import settings
from django.db.models import Count
import os
import time
import uuid
from PIL import Image, ImageFont, ImageDraw

ADDRESS = settings.MEDIA_ROOT + 'pdf/'


# ADDRESS = 'D:/photos/files/ST/workflow/file/'
# ADDRESS = 'E:/delpdf/'


def approvel(name, pdf_path, ser_img, ser_num, can_size, height):
    m = 0
    list2 = []
    time_staff = str(uuid.uuid4())
    for pro_name in name:
        if pro_name['username']:
            uname = User.objects.filter(username=pro_name['username']).values("last_name")[0]["last_name"]
        else:
            uname = str(m)
            pro_name['username'] = str(m)
        msn = pro_name['msn']
        kepp_pic = gen_dummy_sign_picture(uname, msn, canvas_size=can_size)
        jpg_name = ADDRESS + pro_name["username"] + ".jpg"
        kepp_pic.save(jpg_name)
        list2.append(jpg_name)
        m += 1
    width = 2  # 21cm
    height = height  # 1.5cm
    path = pdf_path
    size_w = 132 / UNIT_CM
    size_h = 44 / UNIT_CM
    form_w = 180 / UNIT_CM
    form_h = 30 / UNIT_CM
    width -= 1
    all_twice = len(list2)
    if all_twice <= 5:
        for i in range(all_twice):
            _new_file = ADDRESS + time_staff + "%d.pdf" % i
            # print(path[i])
            pdf = PdfSign(
                path_pdf=path,
                path_image=list2[i],
                sign_size_width=size_w,
                sign_size_height=size_h,
                sign_location_x=width,
                sign_location_y=height,
                form_size_width=form_w,
                form_size_height=form_h,
                form_location_x=22.5,
                form_location_y=0,
                form_img=ser_img,
                serial_num=ser_num,
                size_unit=UNIT_CM,
                new_file=_new_file
            )
            # print(pdf.pdf_info())
            pdf.do_sign()
            width += 0.5
            width += size_w
            list2.append(path)
            path = _new_file
            # width2 = width - (size_w * all_twice + 0.5 * all_twice + 1)
            # print(width2)
            # width3 = int(width - width2)
            # print(width3)
            # for i in range(all_twice):
            #     width3 -= size_w
            #     if width3 < 0:
            #         break
            #     _new_file = ADDRESS+time_staff+"%d.pdf" % i
            #     # print(path[i])
            #     pdf = PdfSign(
            #         path_pdf=path,
            #         path_image=list2[i],
            #         sign_size_width=size_w,
            #         sign_size_height=size_h,
            #         sign_location_x=width3,
            #         sign_location_y=height,
            #         size_unit=UNIT_CM,
            #         new_file=_new_file
            #     )
            #     # print(pdf.pdf_info())
            #     pdf.do_sign()
            #     width3 -= 0.5
            #     list2.append(path)
            #     path = _new_file
    else:

        # width2 = width - (size_w * 5 + 0.5 * 5 + 1)
        # width3 = int(width - width2)
        # print(width3)
        line = int(all_twice / 5) * 5
        twice2 = int(all_twice / 5)
        # print(twice2)
        height2 = height + (2 * (twice2 + 1))
        yu = int(all_twice % 5)
        # print(yu)
        # print(height2)
        for i in range(line):
            # print(i,height2)
            # print(heigh)
            # width3 -= size_w
            # if i>=5:
            if i % 5 == 0:
                height2 = height2 - 2
                width = 1
                # width3 = 26 - size_w
                # print(width3,height)
            else:
                height2 = height2
            # print(height2,width)
            if width < 0:
                break
            _new_file = ADDRESS + time_staff + "%d.pdf" % i
            pdf = PdfSign(
                path_pdf=path,
                path_image=list2[i],
                sign_size_width=size_w,
                sign_size_height=size_h,
                sign_location_x=width,
                sign_location_y=height2,
                form_size_width=form_w,
                form_size_height=form_h,
                form_location_x=22.5,
                form_location_y=0,
                form_img=ser_img,
                serial_num=ser_num,
                size_unit=UNIT_CM,
                new_file=_new_file
            )
            # print(width,height)
            pdf.do_sign()
            width += 0.5
            width += size_w
            list2.append(path)
            path = _new_file
        path = ADDRESS + time_staff + "%d.pdf" % (line - 1)
        # print(path)
        # width2 = width - (size_w * 5 + 0.5 * 5 + 1)
        # width3 = -3.95
        height = height2 - 2
        width = 1
        # print(height)
        for j in range(line, int(line + yu)):
            # height = 0.7
            # width3 += size_w
            if width < 0:
                break
            _new_file = ADDRESS + time_staff + "%d.pdf" % j

            pdf = PdfSign(
                path_pdf=path,
                path_image=list2[j],
                sign_size_width=size_w,
                sign_size_height=size_h,
                sign_location_x=width,
                sign_location_y=height,
                form_size_width=form_w,
                form_size_height=form_h,
                form_location_x=22.5,
                form_location_y=0,
                form_img=ser_img,
                serial_num=ser_num,
                size_unit=UNIT_CM,
                new_file=_new_file
            )
            # print(width,height)
            pdf.do_sign()
            width += 0.5
            width += size_w
            list2.append(path)
            path = _new_file
            # width2 = width - (size_w * 5 + 0.5 * 5 + 1)
            # width3 = int(width - width2)
            # # print(width3)
            # line = int(all_twice / 5) * 5
            # # print(line)
            # yu = int(all_twice % 5)
            # # print(yu)
            # for i in range(line):
            #     width3 -= size_w
            #     # if i>=5:
            #     if i % 5 == 0:
            #         # print('ddddd')
            #         height = height + 2
            #         width3 = 26 - size_w
            #         # print(width3,height)
            #     else:
            #         height = height
            #     if width3 < 0:
            #         break
            #     print(height,width3)
            #     _new_file = ADDRESS+time_staff+"%d.pdf" % i
            #     # print(path[i])
            #     pdf = PdfSign(
            #         path_pdf=path,
            #         path_image=list2[i],
            #         sign_size_width=size_w,
            #         sign_size_height=size_h,
            #         sign_location_x=width3,
            #         sign_location_y=height,
            #         size_unit=UNIT_CM,
            #         new_file=_new_file
            #     )
            #     pdf.do_sign()
            #     width3 -= 0.5
            #     list2.append(path)
            #     path = _new_file
            # path = ADDRESS+time_staff+"%d.pdf" % (line-1)
            # # print(path)
            # # width2 = width - (size_w * 5 + 0.5 * 5 + 1)
            # width3 = -3.95
            # for j in range(line,int(line+yu)):
            #     height = 1.2
            #     width3 += size_w
            #     if width3 < 0:
            #         break
            #     _new_file = ADDRESS+time_staff+"%d.pdf" % j
            #     # print(path[i])
            #     pdf = PdfSign(
            #         path_pdf=path,
            #         path_image=list2[j],
            #         sign_size_width=size_w,
            #         sign_size_height=size_h,
            #         sign_location_x=width3,
            #         sign_location_y=height,
            #         size_unit=UNIT_CM,
            #         new_file=_new_file
            #     )
            #     pdf.do_sign()
            #     width3 += 0.5
            #     list2.append(path)
            #     path = _new_file
    return path, list2


def by_approval(sign_all, path, time_staff, people, sign_people, ser_img, ser_num, can_size, height):
    # 判斷 sign_people

    if people > 5:
        sign_twice = int(people / 5)
        width = 2  # 21cm
        height = height + 2 * (sign_twice + 1)
        k = 0
        size_w = 132 / UNIT_CM
        size_h = 44 / UNIT_CM
        form_w = 180 / UNIT_CM
        form_h = 30 / UNIT_CM
        width -= 1
        # width2 = width - (size_w * 5 + 0.5 * 5 + 1)
        # width3 = int(width - width2)

        # height2 = height + 2*(sign_twice+1)
        line = int(sign_people / 5) * 5
        yu = int(sign_people % 5)
        list1 = []
        # print(sign_all)
        # print(height,height2)
        for sign_info in sign_all:
            # print(sign_info['sign_img'],sign_info['username'])
            sign_img = Image.open(sign_info['sign_img'])  # 裁剪照片
            sign_img.thumbnail((64, 41))
            p = ADDRESS + sign_info['username'] + ".jpg"
            # print(p)
            sign_img.save(p)
            sign_img.close()
            # print(p)
            g = gen_sign_picture(p, sign_info["sign_title"], sign_info["sign_time"],
                                 sign_font_color=sign_info["sign_color"], canvas_size=can_size)
            # p = ADDRESS+sign_info['username'] + ".jpg"
            g.save(p)
            # width3 -= size_w
            # page_num("ETS0011708140001 頁碼：1/1", "E:/delpdf/test3.jpg")
            if k % 5 == 0:
                height = height - 2
                width = 1
                # print(height)
                # width3 = 26 - size_w
                # print(width3,height)
            else:
                height = height
            if width < 0:
                break
            _new_file = ADDRESS + time_staff + '%d.pdf' % k
            # print(width,height)
            pdf = PdfSign(
                path_pdf=path,
                path_image=p,
                sign_size_width=size_w,
                sign_size_height=size_h,
                sign_location_x=width,
                sign_location_y=height,
                form_size_width=form_w,
                form_size_height=form_h,
                form_location_x=22.5,
                form_location_y=0,
                form_img=ser_img,
                serial_num=ser_num,
                size_unit=UNIT_CM,
                new_file=_new_file
            )
            # print(pdf.pdf_info())
            pdf.do_sign()
            width += 0.5
            width += size_w
            list1.append(path)
            path = _new_file
            k += 1
        if line - 1 < 0:
            return path, list1
        path = ADDRESS + time_staff + "%d.pdf" % (line - 1)
        # print(path,type(sign_people))
        # width2 = width - (size_w * 5 + 0.5 * 5 + 1)
        # print(line,line+yu)

        width3 = 1
        # height = height -2
        # print(height,line,yu)
        for j in range(line, int(line + yu)):
            if sign_people < line:
                break
            data = sign_all[j]
            sign_img = Image.open(data['sign_img'])  # 裁剪照片
            sign_img.thumbnail((64, 41))
            p = ADDRESS + data['username'] + ".jpg"
            # print(p)
            sign_img.save(p)
            sign_img.close()
            # print(p)
            # g = gen_sign_picture(p, sign_info["sign_title"],sign_info["sign_time"])
            g = gen_sign_picture(p, data["sign_title"], data["sign_time"])
            # p = ADDRESS+data['username'] + ".jpg"
            g.save(p)
            # print(height)

            if width3 < 0:
                break
            _new_file = ADDRESS + time_staff + "%d.pdf" % j
            # print(path[i])
            pdf = PdfSign(
                path_pdf=path,
                path_image=p,
                sign_size_width=size_w,
                sign_size_height=size_h,
                sign_location_x=width3,
                sign_location_y=height,
                form_size_width=form_w,
                form_size_height=form_h,
                form_location_x=22.5,
                form_location_y=0,
                form_img=ser_img,
                serial_num=ser_num,
                size_unit=UNIT_CM,
                new_file=_new_file
            )
            pdf.do_sign()
            width3 += 0.5
            width3 += size_w
            list1.append(path)
            path = _new_file
        return path, list1
    else:
        width3 = 2  # 21cm
        height = height  # 1.5cm
        width3 -= 1
        size_w = 132 / UNIT_CM
        size_h = 44 / UNIT_CM
        form_w = 180 / UNIT_CM
        form_h = 30 / UNIT_CM
        # width2 = width - (size_w * people + 0.5 * people + 1)
        # width3 = int(width - width2)
        h = 0
        list3 = []
        # for i in range(5):
        for sign_info in sign_all:
            sign_img = Image.open(sign_info['sign_img'])  # 裁剪照片
            sign_img.thumbnail((64, 41))
            # print(sign_img.size)
            p = ADDRESS + sign_info['username'] + ".jpg"
            sign_img.save(p)
            sign_img.close()
            g = gen_sign_picture(p, sign_info["sign_title"], sign_info["sign_time"])
            g.save(p)
            # g = gen_sign_picture(sign_info['sign_img'], sign_info["sign_title"],sign_info["sign_time"])
            # p = ADDRESS+sign_info['username'] + ".jpg"
            # g.save(p)
            # for i in range(5):
            # width3 -= size_w
            _new_file = ADDRESS + time_staff + '%d.pdf' % h

            pdf = PdfSign(
                path_pdf=path,
                path_image=p,
                sign_size_width=size_w,
                sign_size_height=size_h,
                sign_location_x=width3,
                sign_location_y=height,
                form_size_width=form_w,
                form_size_height=form_h,
                form_location_x=22.5,
                form_location_y=0,
                form_img=ser_img,
                serial_num=ser_num,
                size_unit=UNIT_CM,
                new_file=_new_file
            )
            # print(pdf.pdf_info())
            pdf.do_sign()
            width3 += 0.5
            width3 += size_w
            list3.append(path)
            path = _new_file
            h += 1
        return path, list3


def approvel2(name, pdf_path, ser_img, ser_num, can_size, height):
    # print('sdassa')
    m = 0
    list2 = []
    time_staff = str(uuid.uuid4())
    for pro_name in name:
        if pro_name['username']:
            uname = User.objects.filter(username=pro_name['username']).values("last_name")[0]["last_name"]
        else:
            uname = str(m)
            pro_name['username'] = str(m)
        msn = pro_name['msn']
        kepp_pic = gen_dummy_sign_picture(uname, msn, canvas_size=can_size)
        jpg_name = ADDRESS + pro_name["username"] + ".jpg"
        kepp_pic.save(jpg_name)
        list2.append(jpg_name)
        m += 1
    width = 1.5  # 21cm
    height = height  # 1.5cm
    path = pdf_path
    size_w = 132 / UNIT_CM
    size_h = 44 / UNIT_CM
    form_w = 180 / UNIT_CM
    form_h = 30 / UNIT_CM
    width -= 1
    all_twice = len(list2)
    if all_twice <= 4:
        for i in range(all_twice):
            _new_file = ADDRESS + time_staff + "%d.pdf" % i
            # print(path[i])
            # print(width)
            pdf = PdfSign(
                path_pdf=path,
                path_image=list2[i],
                sign_size_width=size_w,
                sign_size_height=size_h,
                sign_location_x=width,
                sign_location_y=height,
                form_size_width=form_w,
                form_size_height=form_h,
                form_location_x=15,
                form_location_y=0,
                form_img=ser_img,
                serial_num=ser_num,
                size_unit=UNIT_CM,
                new_file=_new_file
            )
            # print(pdf.pdf_info())
            pdf.do_sign()
            width += 0.5
            width += size_w
            list2.append(path)
            path = _new_file
    else:
        line = int(all_twice / 4) * 4
        # twice2 = int(all_twice / 4) + (all_twice % 4 > 0 and 1 or 0) - 1
        twice2 = int(all_twice / 4)
        height2 = height + (2 * (twice2 + 1))

        yu = int(all_twice % 4)
        # print(yu)
        # print(height2)
        for i in range(line):
            if i % 4 == 0:
                height2 = height2 - 2
                width = 0.5
            else:
                height2 = height2
            if width < 0:
                break
            _new_file = ADDRESS + time_staff + "%d.pdf" % i
            # print('sadssadaw')
            # print(path[i])
            # print(height2)
            pdf = PdfSign(
                path_pdf=path,
                path_image=list2[i],
                sign_size_width=size_w,
                sign_size_height=size_h,
                sign_location_x=width,
                sign_location_y=height2,
                form_size_width=form_w,
                form_size_height=form_h,
                form_location_x=15,
                form_location_y=0,
                form_img=ser_img,
                serial_num=ser_num,
                size_unit=UNIT_CM,
                new_file=_new_file
            )
            # print(width,height)
            pdf.do_sign()
            width += 0.5
            width += size_w
            list2.append(path)
            path = _new_file
        path = ADDRESS + time_staff + "%d.pdf" % (line - 1)
        height = height2 - 2
        width = 0.5
        # print(height)
        for j in range(line, int(line + yu)):
            # height = 0.7
            # width3 += size_w
            if width < 0:
                break
            _new_file = ADDRESS + time_staff + "%d.pdf" % j
            pdf = PdfSign(
                path_pdf=path,
                path_image=list2[j],
                sign_size_width=size_w,
                sign_size_height=size_h,
                sign_location_x=width,
                sign_location_y=height,
                form_size_width=form_w,
                form_size_height=form_h,
                form_location_x=15,
                form_location_y=0,
                form_img=ser_img,
                serial_num=ser_num,
                size_unit=UNIT_CM,
                new_file=_new_file
            )
            # print(width,height)
            pdf.do_sign()
            width += 0.5
            width += size_w
            list2.append(path)
            path = _new_file

    return path, list2


def by_approval2(sign_all, path, time_staff, people, sign_people, ser_img, ser_num, can_size, height):
    if people > 4:
        # sign_twice = int(people / 4) + (people % 4 > 0 and 1 or 0) - 1
        sign_twice = int(people / 4)
        width = 1.5  # 21cm
        height = height + 2 * (sign_twice + 1)
        k = 0
        size_w = 132 / UNIT_CM
        size_h = 44 / UNIT_CM
        form_w = 180 / UNIT_CM
        form_h = 30 / UNIT_CM
        width -= 1
        line = int(sign_people / 4) * 4
        yu = int(sign_people % 4)
        list1 = []
        for sign_info in sign_all:
            sign_img = Image.open(sign_info['sign_img'])  # 裁剪照片
            sign_img.thumbnail((64, 41))
            p = ADDRESS + sign_info['username'] + ".jpg"
            sign_img.save(p)
            sign_img.close()
            # print(p)
            g = gen_sign_picture(p, sign_info["sign_title"], sign_info["sign_time"],
                                 sign_font_color=sign_info["sign_color"], canvas_size=can_size)
            g.save(p)
            if k % 4 == 0:
                height = height - 2
                width = 0.5
            else:
                height = height
            if width < 0:
                break
            _new_file = ADDRESS + time_staff + '%d.pdf' % k
            pdf = PdfSign(
                path_pdf=path,
                path_image=p,
                sign_size_width=size_w,
                sign_size_height=size_h,
                sign_location_x=width,
                sign_location_y=height,
                form_size_width=form_w,
                form_size_height=form_h,
                form_location_x=15,
                form_location_y=0,
                form_img=ser_img,
                serial_num=ser_num,
                size_unit=UNIT_CM,
                new_file=_new_file
            )
            pdf.do_sign()
            width += 0.5
            width += size_w
            list1.append(path)
            path = _new_file
            k += 1
        if line - 1 < 0:
            return path, list1
        path = ADDRESS + time_staff + "%d.pdf" % (line - 1)
        width3 = 0.5
        for j in range(line, int(line + yu)):
            if sign_people < line:
                break
            data = sign_all[j]
            sign_img = Image.open(data['sign_img'])  # 裁剪照片
            sign_img.thumbnail((64, 41))
            p = ADDRESS + data['username'] + ".jpg"
            # print(p)
            sign_img.save(p)
            sign_img.close()
            g = gen_sign_picture(p, data["sign_title"], data["sign_time"])
            g.save(p)

            if width3 < 0:
                break
            _new_file = ADDRESS + time_staff + "%d.pdf" % j
            # print(path[i])
            pdf = PdfSign(
                path_pdf=path,
                path_image=p,
                sign_size_width=size_w,
                sign_size_height=size_h,
                sign_location_x=width3,
                sign_location_y=height,
                form_size_width=form_w,
                form_size_height=form_h,
                form_location_x=15,
                form_location_y=0,
                form_img=ser_img,
                serial_num=ser_num,
                size_unit=UNIT_CM,
                new_file=_new_file
            )
            pdf.do_sign()
            width3 += 0.5
            width3 += size_w
            list1.append(path)
            path = _new_file
        return path, list1
    else:
        width3 = 1.5  # 21cm
        height = height  # 1.5cm
        width3 -= 1
        size_w = 132 / UNIT_CM
        size_h = 44 / UNIT_CM
        form_w = 180 / UNIT_CM
        form_h = 30 / UNIT_CM
        h = 0
        list3 = []
        # for i in range(5):
        for sign_info in sign_all:
            sign_img = Image.open(sign_info['sign_img'])  # 裁剪照片
            sign_img.thumbnail((64, 41))
            # print(sign_img.size)
            p = ADDRESS + sign_info['username'] + ".jpg"
            sign_img.save(p)
            sign_img.close()
            g = gen_sign_picture(p, sign_info["sign_title"], sign_info["sign_time"])
            g.save(p)
            _new_file = ADDRESS + time_staff + '%d.pdf' % h

            pdf = PdfSign(
                path_pdf=path,
                path_image=p,
                sign_size_width=size_w,
                sign_size_height=size_h,
                sign_location_x=width3,
                sign_location_y=height,
                form_size_width=form_w,
                form_size_height=form_h,
                form_location_x=15,
                form_location_y=0,
                form_img=ser_img,
                serial_num=ser_num,
                size_unit=UNIT_CM,
                new_file=_new_file
            )
            # print(pdf.pdf_info())
            pdf.do_sign()
            width3 += 0.5
            width3 += size_w
            list3.append(path)
            path = _new_file
            h += 1
        return path, list3


def delete_pdf(path, file_path=''):
    # print(file_path)
    if file_path != '':
        try:
            path.remove(file_path)
        except:
            pass
    try:
        for filename in path:
            # filename.close()
            if os.path.exists(filename):
                os.remove(filename)
            else:
                return 'No File'
        return 'Success'
    except Exception as e:
        return str(e)


from wfs import models
from files.models import TbApplyform
from django.conf import settings


def form_pdf(record_id, filenamelist):
    name = []
    if not filenamelist:
        return ''
    file_list = []
    for filename in filenamelist:
        name = []
        for i in WorkflowApprovalRecord.objects.filter(workflow_record_id=record_id, status=1):
            name.append({'username': '', 'msn': '發起'})
        group = models.NodeGroup.objects.filter(workflowrecord_id=record_id).order_by('order_number')
        for i in group:
            node = models.NodeCase.objects.filter(group_id=i.id).order_by('order_number')
            list = [i.order_number for i in node]
            if len(set(list)) == 1 and node[0].user_mode.lower() == 'oneOnly'.lower():
                name.append({'username': '', 'msn': i.name})
            else:
                for row in node:
                    name.append({'username': row.approver, 'msn': i.name})
        pdf_path = filename
        aa = TbApplyform.objects.filter(wrecord_id=record_id)
        size = (132, 44)
        high = 1.2
        if aa[0].customer_id or aa[0].project_id:
            # size = (66, 22)
            high = 0.8
        # d,lists = approvel(name,pdf_path.replace('//','/'),settings.MEDIA_ROOT+"pdf/"+aa[0].card_id+'.jpg',aa[0].card_id,)
        if aa[0].layout == 'vertical':
            d, lists = approvel2(name, filename.replace('//', '/'),
                                 settings.MEDIA_ROOT + 'pdf/' + aa[0].card_id + '.jpg', aa[0].card_id, size,high)
        else:
            d, lists = approvel(name, filename.replace('//', '/'),
                                settings.MEDIA_ROOT + 'pdf/' + aa[0].card_id + '.jpg', aa[0].card_id, size,high)
        delete_pdf(lists, pdf_path)
        file_list.append(d)
    Workflowrecord.objects.filter(id=record_id).update(pdf=file_list)
    return file_list


def by_pdf(record_id, pathlist=None):
    if not pathlist:
        pathlist = eval(Workflowrecord.objects.filter(id=record_id)[0].pdf)
    if not pathlist:
        return pathlist
    file_list = []
    for path in pathlist:
        appRecord = models.WorkflowApprovalRecord.objects.filter(workflow_record_id=record_id).order_by('order_number')
        number = len(appRecord.values('order_number').distinct())
        if len(appRecord) < 1:
            return ''  # Workflowrecord.objects.filter(id=record_id)[0].no
        else:
            sign_all = []
            if '-' in appRecord[len(appRecord) - 1].next:
                group, node = appRecord[len(appRecord) - 1].next.split('-')
                node = 1 if node == '0' else node

            else:
                appRecord2 = WorkflowApprovalRecord.objects.filter(id=appRecord[len(appRecord) - 1].next)
                group, node = appRecord2[len(appRecord2) - 1].next.split('-')
            number += 1
            groupCase = NodeCase.objects.filter(group_id=group)

            if groupCase[0].user_mode.lower() == 'oneOnly'.lower():
                list = len(set([i.order_number for i in groupCase]))
            else:
                list = len(groupCase)

            if list >= int(node):  # 判斷當前節點是否是最高一個節點
                for index in range(int(node), list):
                    node = models.NodeCase.objects.filter(group_id=group).order_by('order_number')
                    list = [i.order_number for i in node]
                    if len(set(list)) == 1 and node[0].user_mode.lower() == 'oneOnly'.lower():
                        number += 1
                    else:
                        number += 1


                for i in NodeGroup.objects.filter(workflowrecord_id=record_id, id__gt=group):
                    node = models.NodeCase.objects.filter(group_id=i.id).order_by('order_number')
                    list = [i.order_number for i in node]
                    if len(set(list)) == 1 and node[0].user_mode.lower() == 'oneOnly'.lower():
                        number += 1
                    else:
                        for row in node:
                            number += 1

            else:  # 當節點為最後等於節點和的話就需要找到下一個組
                for i in NodeGroup.objects.filter(workflowrecord_id=record_id, id__gt=group):
                    node = models.NodeCase.objects.filter(group_id=i.id).order_by('order_number')
                    list = [i.order_number for i in node]
                    if len(set(list)) == 1 and node[0].user_mode.lower() == 'oneOnly'.lower():
                        number += 1
                    else:
                        for row in node:
                            number += 1
            imgfile = ''

            for row in appRecord.filter(status=1):
                color = 'black'
                if row.action not in ['駁回', '發起']:
                    if '-' in row.next:
                        group, node = row.next.split('-')
                    else:
                        appRecord2 = WorkflowApprovalRecord.objects.filter(id=row.next)
                        group, node = appRecord2[0].next.split('-')
                    if node == '0' and row.approver == appRecord[0].approver:
                        row.action = '申請人'
                    elif row.approver == appRecord[0].approver and '-' not in row.next:
                        row.action = '申請人'
                    else:
                        groups = NodeGroup.objects.filter(id=group)
                        row.action = groups[0].name
                elif row.action == '駁回':
                    color = 'red'
                if not row.signature:
                    # imgfile = appimg(row.approver)
                    sign_all.append({'sign_img': signImg(User.objects.filter(username=row.approver)[0].last_name,
                                                         settings.MEDIA_ROOT + 'pdf/' + row.approver + ".png"),
                                     'username': row.approver, 'sign_title': row.action, 'sign_time': row.end_time,
                                     'sign_color': color})
                    # sign_all.append({'sign_img':imgfile,'username':row.approver,'sign_title':row.action,'sign_time':row.end_time})
                    # sign_all.append({'sign_img':imgfile,'username':row.approver,'sign_title':row.action,'sign_time':row.end_time})

                else:
                    #     sign_all.append({'sign_img':'D:/photos/files/ST/workflow/file/vi.png','sign_title':row.action,'username':row.approver,'sign_time':row.end_time})'
                    sign_all.append({'sign_img': row.signature.replace('files',
                                                                       settings.MEDIA_ROOT) if 'files' in row.signature else settings.MEDIA_ROOT + row.signature,
                                     'sign_title': row.action, 'username': row.approver, 'sign_time': row.end_time,
                                     'sign_color': color})

            sis = len(appRecord.filter(status=1))
            # if number >= 10:
            #     if sis % 5 != 0:
            #             sign_people = (int(sis / 5) + 1) * 5
            #     else:
            #         sign_people = sis
            # else:
            #     sign_people = sis
            aa = TbApplyform.objects.filter(wrecord_id=record_id)
            size = (132, 44)
            high = 1.2
            if aa[0].customer_id or aa[0].project_id:
                # size = (66, 22)
                high =0.8
            if aa[0].layout == "vertical":
                # if number % 4 != 0:
                #     number += 1
                d, lists = by_approval2(sign_all=sign_all, path=path, people=number, sign_people=sis,
                                        time_staff=str(uuid.uuid4()), ser_num=aa[0].card_id,
                                        ser_img=settings.MEDIA_ROOT + "pdf/" + aa[0].card_id + '.jpg', can_size=size, height=high)
            else:
                d, lists = by_approval(sign_all=sign_all, path=path, people=number, sign_people=sis,
                                       time_staff=str(uuid.uuid4()), ser_num=aa[0].card_id,
                                       ser_img=settings.MEDIA_ROOT + "pdf/" + aa[0].card_id + '.jpg', can_size=size,height=high)
            delete_pdf(lists, path)
            file_list.append(d)
    return file_list


def by_form_pdf(record_id):
    try:
        filenamelist = eval(TbApplyform.objects.filter(wrecord_id=record_id)[0].pdf)
    except Exception as e:
        return ""
    file_list, sss = [], []
    # filename = 'D:/photos/files/ST/workflow/file/'+eval(TbApplyform.objects.filter(wrecord_id=record_id)[0].file1)['href'].split('/')[-1]
    for filename1 in filenamelist:
        name = []
        filename = filename1['href']

        appRecord = models.WorkflowApprovalRecord.objects.filter(workflow_record_id=record_id).order_by('order_number')
        for index, value in enumerate(appRecord):
            # NodeGroup.objects.filter(id=i.next.split('-')[0])
            if not value.next:
                continue
            if value.next == '0':
                name.append({'username': value.approver, 'msn': '發起'})
            elif '-' in value.next:
                if index != 0:
                    if value.next == appRecord[index - 1].next:
                        continue
                if value.next.split('-')[1] == '0' and value.approver == appRecord[0].approver:
                    name.append({'username': value.approver, 'msn': '申請人'})
                    continue
                name.append(
                    {'username': value.approver, 'msn': NodeGroup.objects.filter(id=value.next.split('-')[0])[0].name})
            else:
                nex = WorkflowApprovalRecord.objects.filter(id=value.next)[0]
                if value.approver == appRecord[0].approver:
                    name.append({'username': value.approver, 'msn': '申請人'})
                    continue
                name.append(
                    {'username': value.approver, 'msn': NodeGroup.objects.filter(id=nex.next.split('-')[0])[0].name})
        sign_all = []
        # group,node = appRecord[len(appRecord)-1].next.split('-')

        if '-' in appRecord[len(appRecord) - 1].next:
            group, node = appRecord[len(appRecord) - 1].next.split('-')
            node = 1 if node == '0' else node
        else:
            appRecord = WorkflowApprovalRecord.objects.filter(id=appRecord[len(appRecord) - 1].next)
            group, node = appRecord[len(appRecord) - 1].next.split('-')
        groupCase = NodeCase.objects.filter(group_id=group)
        number = appRecord
        list = set([i.order_number for i in groupCase])

        if len(list) >= int(node):  # 判斷當前節點是否是最高一個節點
            for index in range(int(node), len(groupCase) + 1):
                node = models.NodeCase.objects.filter(group_id=group, order_number=index).order_by('order_number')
                list = [i.order_number for i in node]
                if len(set(list)) == 1 and node[0].user_mode.lower() == 'oneOnly'.lower():
                    name.append({'username': '', 'msn': NodeGroup.objects.filter(id=group)[0].name})
                else:
                    for row in node:
                        name.append({'username': row.approver, 'msn': NodeGroup.objects.filter(id=group)[0].name})
            for i in NodeGroup.objects.filter(workflowrecord_id=record_id, id__gt=group):
                node = models.NodeCase.objects.filter(group_id=i.id).order_by('order_number')
                list = [i.order_number for i in node]
                if len(set(list)) == 1 and node[0].user_mode.lower() == 'oneOnly'.lower():
                    name.append({'username': node[0].approver, 'msn': i.name})
                else:
                    for row in node:
                        name.append({'username': row.approver, 'msn': i.name})
        else:  # 當節點為最後等於節點和的話就需要找到下一個組
            for i in NodeGroup.objects.filter(workflowrecord_id=record_id, id__gte=group):
                node = models.NodeCase.objects.filter(group_id=i.id).order_by('order_number')
                list = [i.order_number for i in node]
                if len(set(list)) == 1 and node[0].user_mode.lower() != 'oneOnly'.lower():
                    name.append({'username': node[0].approver, 'msn': i.name})
                else:
                    for row in node:
                        name.append({'username': row.approver, 'msn': i.name})
        aa = TbApplyform.objects.filter(wrecord_id=record_id)
        if aa[0].customer_id or aa[0].project_id:
            size = (132, 44)
            high =0.8
        else:
            size = (132, 44)
            high =1.2
        if aa[0].layout == 'vertical':
            d, lists = approvel2(name, filename,
                                 settings.MEDIA_ROOT + 'pdf/' + aa[0].card_id + '.jpg', aa[0].card_id, size,high)
        else:

            d, lists = approvel(name, filename,
                                settings.MEDIA_ROOT + 'pdf/' + aa[0].card_id + '.jpg', aa[0].card_id, size,high)
        file_list.append(d)
        delete_pdf(lists, filename)
        sss += by_pdf(record_id, [d])
    Workflowrecord.objects.filter(id=record_id).update(pdf=file_list)
    return sss


import threading


def th(id):
    pdf = threading.Thread(target=by_pdf, args=(id))
    pdf.setDaemon(True)
    pdf.start()


def th2(id):
    pdf = threading.Thread(target=by_form_pdf, args=(id))
    pdf.setDaemon(True)
    pdf.start()


def born_pdf(img, f_pdf):
    # img = imgname
    fp = open(img, 'rb')
    im = Image.open(fp)
    fp.close()
    x, y = im.size
    # f_pdf = pdf_path
    (w, h) = landscape(A4)
    lh = int(h) - int(y)
    lw = (int(w) - int(x)) / 2
    # print(h)
    c = canvas.Canvas(f_pdf, pagesize=landscape(A4))
    c.drawImage(img, lw, lh, x, y)
    c.save()


def signImg(signName, img_path):
    if len(signName) >= 4:
        im = Image.new("RGB", (62, 41), (255, 255, 255))
        dr = ImageDraw.Draw(im)
        font = ImageFont.truetype(ADDRESS + "simcu.TTC", 10)
        dr.text((0, 10), signName, font=font, fill="#000000")
        im.save(img_path)
    else:
        loc_x = 0 if len(signName) == 3 else 10
        im = Image.new("RGB", (62, 41), (255, 255, 255))
        dr = ImageDraw.Draw(im)
        font = ImageFont.truetype(ADDRESS + "simcu.TTC", 20)
        dr.text((loc_x, 10), signName, font=font, fill="#000000")
        im.save(img_path)
    return img_path


def page_num(form_num, img_path):
    im = Image.new("RGB", (180, 30), (255, 255, 255))
    dr = ImageDraw.Draw(im)
    font = ImageFont.truetype(ADDRESS + "simcu.TTC", 12)
    dr.text((10, 10), form_num, font=font, fill="#000000")
    im.save(img_path)


if __name__ == '__main__':
    page_num("JFDGHKFDH 頁碼：1/1", "E:/delpdf/test3.jpg")
    # name = ["F1331855","F1330319","F1330314"]
    # pdf_path =ADDRESS+ "444.pdf"
    # approvel(name,pdf_path)
